package de.fuberlin.dbs.wm.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import de.fuberlin.dbs.wm.dao.model.Group;
import de.fuberlin.dbs.wm.dao.model.TeamStat;
import de.fuberlin.dbs.wm.dao.util.ResultMapper;
import de.fuberlin.dbs.wm.util.NotAllowedException;

public class GroupDao extends Dao{
	
	public static List<TeamStat> printStandings(Group group, String tournament) throws SQLException, NotAllowedException {
		if(Dao.hasGroupReadAccess(group.getName())) {
			String sql = "select * from table(GET_GROUP_TABLE('" + group.getName() + "', '" + tournament + "')) order by Punkte DESC, Tore DESC";
			List<TeamStat> list = db.mapQuery(sql, new ResultMapper<TeamStat>() {
				@Override
				public TeamStat mapResult(ResultSet rs) throws SQLException {
					TeamStat teamStat = new TeamStat(
							rs.getInt("Punkte"),
							rs.getInt("Tore"),
							rs.getInt("Gegentore"),
							rs.getString("Team"),
							rs.getInt("Spiele"),
							rs.getInt("Gewonnen"),
							rs.getInt("Verloren"),
							rs.getInt("Unentschieden")
							);
					return teamStat;
				}			
			});
			return list;
		} else throw new NotAllowedException();
	}
	
	public static List<Group> getGroups(String tournament) throws SQLException {
		String sql = "select * from Gruppe where " +
		"Turnier_Name like '" + tournament + "' order by Kennung";
		List<Group> list = db.mapQuery(sql, new ResultMapper<Group>() {
			@Override
			public Group mapResult(ResultSet rs) throws SQLException {
				Group group = new Group(rs.getString("Kennung"), rs.getString("Turnier_Name"));
				return group;
			}			
		});
		return list;
	}
}
